﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;

using System.Windows;
using DataMongo;
using DataMongo.Entities;


namespace MVCMongo
{
    public class RssReader
    {
        public static IEnumerable<Rss> GetRssFeed(string feedUrl)
        {
            var rssKing = new List<Rss>();
            try
            {

                WebClient client = new WebClient();
                string result = client.DownloadString(feedUrl);
                // Convert string to XDocument.
                XDocument xmlDoc = XDocument.Parse(result);
                XNamespace m = "http://search.yahoo.com/mrss/";
            

                //var rssKing = (from story in xmlDoc.Descendants("item")
                //    select new Rss
                //    {
                //        Title = ((string) story.Element("title")),
                //        Link = ((string) story.Element("link")),
                //        Description = ((string) story.Element("description")),
                //        PublishDate = ((string) story.Element("pubDate")),
                //        ImageUrl = story.Element(m + "thumbnail").Attribute("url").Value

                //    }).Take(20).ToList();

                foreach (var story in xmlDoc.Descendants("item"))
                {
                    var xElement = story.Element(m + "thumbnail");

                    var rss = new Rss()
                    {
                        Title = ((string)story.Element("title")),
                        Link = ((string)story.Element("link")),
                        Description = ((string)story.Element("description")),
                        PublishDate = ((string)story.Element("pubDate")),

                    };
                    if (xElement != null)
                    {
                        rss.ImageUrl = xElement.Attribute("url").Value;
                    }
                    rssKing.Add(rss);
                   
                }
                return rssKing;

            }
            catch (Exception e)
            {
                return rssKing;
            }
        }
    }
}